package com.example.zhilierp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhilierp.entity.Role;
import com.example.zhilierp.service.RoleService;
import com.example.zhilierp.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色控制器
 * 处理角色相关的HTTP请求
 */
@RestController
@RequestMapping("/api/role")
@Tag(name = "角色管理", description = "角色管理相关接口")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 分页查询角色列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param roleName 角色名称（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询角色列表", description = "根据条件分页查询角色列表")
    public Result<Page<Role>> page(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(required = false) String roleName) {
        try {
            Page<Role> page = new Page<>(pageNum, pageSize);
            Page<Role> resultPage = roleService.page(page);
            return Result.success(resultPage);
        } catch (Exception e) {
            return Result.error(500, "查询角色列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询角色信息
     * @param id 角色ID
     * @return 角色信息
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询角色信息", description = "根据角色ID获取详细信息")
    public Result<Role> getById(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error(400, "角色ID不能为空");
            }
            Role role = roleService.getById(id);
            if (role == null) {
                return Result.error(404, "角色不存在");
            }
            return Result.success(role);
        } catch (Exception e) {
            return Result.error(500, "查询角色信息失败: " + e.getMessage());
        }
    }

    /**
     * 新增角色
     * @param role 角色信息
     * @return 操作结果
     */
    @PostMapping
    @Operation(summary = "新增角色", description = "创建新角色")
    public Result<Boolean> save(@RequestBody Role role) {
        try {
            if (role == null) {
                return Result.error(400, "角色信息不能为空");
            }
            boolean success = roleService.insertRole(role);
            return success ? Result.success(true) : Result.error(500, "新增角色失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 修改角色
     * @param role 角色信息
     * @return 操作结果
     */
    @PutMapping
    @Operation(summary = "修改角色", description = "更新角色信息")
    public Result<Boolean> update(@RequestBody Role role) {
        try {
            if (role == null || role.getId() == null) {
                return Result.error(400, "角色ID不能为空");
            }
            // 检查角色是否存在
            if (roleService.getById(role.getId()) == null) {
                return Result.error(404, "角色不存在");
            }
            boolean success = roleService.updateRole(role);
            return success ? Result.success(true) : Result.error(500, "修改角色失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 删除角色
     * @param id 角色ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除角色", description = "根据角色ID删除角色")
    public Result<Boolean> delete(@PathVariable Long id) {
        try {
            if (id == null) {
                return Result.error(400, "角色ID不能为空");
            }
            // 检查角色是否存在
            if (roleService.getById(id) == null) {
                return Result.error(404, "角色不存在");
            }
            boolean success = roleService.removeById(id);
            return success ? Result.success(true) : Result.error(500, "删除角色失败");
        } catch (Exception e) {
            return Result.error(500, "删除角色失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除角色
     * @param ids 角色ID数组
     * @return 操作结果
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除角色", description = "批量删除多个角色")
    public Result<Boolean> deleteBatch(@RequestBody Long[] ids) {
        try {
            if (ids == null || ids.length == 0) {
                return Result.error(400, "角色ID数组不能为空");
            }
            boolean success = roleService.deleteRoleByIds(ids);
            return success ? Result.success(true) : Result.error(500, "批量删除角色失败");
        } catch (Exception e) {
            return Result.error(500, "批量删除角色失败: " + e.getMessage());
        }
    }

    /**
     * 修改角色状态
     * @param id 角色ID
     * @param status 状态：0禁用，1启用
     * @return 操作结果
     */
    @PutMapping("/status/{id}")
    @Operation(summary = "修改角色状态", description = "启用或禁用角色")
    public Result<Boolean> changeStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            if (id == null) {
                return Result.error(400, "角色ID不能为空");
            }
            if (status == null || (status != 0 && status != 1)) {
                return Result.error(400, "状态值必须为0或1");
            }
            boolean success = roleService.changeStatus(id, status);
            return success ? Result.success(true) : Result.error(500, "修改角色状态失败");
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取所有角色列表
     * @return 角色列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取所有角色列表", description = "获取系统中所有角色")
    public Result<List<Role>> list() {
        try {
            List<Role> roles = roleService.list();
            return Result.success(roles);
        } catch (Exception e) {
            return Result.error(500, "获取角色列表失败: " + e.getMessage());
        }
    }
}